package org.ManagerSystem.services.Impl;

import org.ManagerSystem.DAO.DepartmentDAO;
import org.ManagerSystem.DTO.PageBean;
import org.ManagerSystem.entity.Department;
import org.ManagerSystem.services.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService{

    @Autowired
    private DepartmentDAO departmentDAO;

    @Override
    public Department queryById(long did){
        return departmentDAO.queryById(did);
    }

    @Override
    public PageBean<Department> queryByPage(int currentPage) {

        //设置每页要显示的记录数
        int pageSize = 5;
        //记录 department 表中记录的总条数
        int totalCount = 0;
        double tc = 0;
        //记录总页数
        Double totalPage = null;
        //记录每页的开始值
        int start=0;
        //记录分页查询出来的集合数据
        List<Department> list;
        //创建 PageBean 的实例
        PageBean<Department> pageBean = new PageBean<Department>();

        //查询总记录数
        totalCount = departmentDAO.findCount();
        tc = totalCount;
        //计算总页数
        totalPage = Math.ceil(tc/pageSize);
        //计算每一页的记录的开始值和结束值
        start = pageSize * (currentPage-1);
        //分页查询每一页的数据
        list = departmentDAO.queryByPage(start , pageSize);

        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setTotalCount(totalCount);
        pageBean.setTotalPage(totalPage.intValue());
        pageBean.setList(list);

        return pageBean;
    }

    @Override
    @Transactional
    public void save(Department department) {
        departmentDAO.save(department);
    }

    @Override
    @Transactional
    public void deleteById(long did) {
        departmentDAO.deleteById(did);
    }

    @Override
    @Transactional
    public void update(Department department) {
        departmentDAO.update(department);
    }

    @Override
    public List<Department> queryAll(long rid , long did){
        List<Department> list = departmentDAO.queryAll();
        if(rid > 1){
            for(int i = 0 ; i<list.size() ; i++){
                if(list.get(i).getDid() == did){
                    Department department = list.get(i);
                    list.clear();
                    System.out.println(list.size()) ;
                    list.add(department);
                }
            }
        }
        return list;
    }
}
